package com.example.demo.util;


import com.example.demo.domin.dto.UserDTO;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;

import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


public class JwtUtil {
        //JWT密钥
    public static final String secretKey="testasdefbadfjslkodkalsldisnvjjaslfjdasjdf";

    public static final Long time=1000l*60*60*24*3;

    public static String getToken(UserDTO user) throws UnsupportedEncodingException {
        Map<String, Object> map = new HashMap<>();
        map.put("alg","HS256");
        map.put("typ","JWT");
        String compact = Jwts.builder().signWith(Keys.hmacShaKeyFor(secretKey.getBytes(StandardCharsets.UTF_8)))
                .claim("userId", user.getUserId())
                .setExpiration(new Date(System.currentTimeMillis() + time))
                .compact();
        return compact;
    }

    public static Claims getClaims(String token) throws UnsupportedEncodingException {
        JwtParser build = Jwts.parser().verifyWith(Keys.hmacShaKeyFor(secretKey.getBytes(StandardCharsets.UTF_8)))
                .build();
        Claims body = build.parseSignedClaims(token).getBody();
        return body;
    }
}
